/**
 * 
 */
package cn.micai.core.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.micai.common.controller.BaseController;
import cn.micai.common.page.Pagination;
import cn.micai.core.bean.BuyCart;
import cn.micai.core.bean.BuyItem;
import cn.micai.core.web.Constants;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.micai.common.web.session.SessionProvider;
import cn.micai.core.bean.product.Brand;
import cn.micai.core.bean.product.Color;
import cn.micai.core.bean.product.Feature;
import cn.micai.core.bean.product.Product;
import cn.micai.core.bean.product.Sku;
import cn.micai.core.bean.product.Type;
import cn.micai.core.query.product.BrandQuery;
import cn.micai.core.query.product.FeatureQuery;
import cn.micai.core.query.product.ProductQuery;
import cn.micai.core.query.product.TypeQuery;
import cn.micai.core.service.product.BrandService;
import cn.micai.core.service.product.ColorService;
import cn.micai.core.service.product.FeatureService;
import cn.micai.core.service.product.ProductService;
import cn.micai.core.service.product.SkuService;
import cn.micai.core.service.product.TypeService;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 前台商品列表
 * 测试
 * 商品列表
 * 商品详情
 * @author XinGuo
 *
 */
@Controller
public class FrontProductController extends BaseController{
	
	@Autowired
	private BrandService brandService; // 品牌
	
	@Autowired
	private ProductService productService; // 商品
	
	@Autowired
	private TypeService typeService; // 商品类型
	
	@Autowired
	private FeatureService featureService; // 商品属性
	
	@Autowired
	private SkuService skuService;//SKU(最新销售单元)
	
	@Autowired
	private ColorService colorService;//颜色
	
	//商品列表页面
	@RequestMapping(value = "/product/display/list.shtml")
	public String list(Integer pageNo,Integer brandId,String brandName,Integer typeId,String typeName,ModelMap model,HttpServletRequest request){

	    //加载购物车信息
		getBuyCartForCookie(model, request);

		//①.加载品牌，类型，材质


		// 3.加载商品属性
		FeatureQuery featureQuery = new FeatureQuery();
		List<Feature> features = featureService.getFeatureList(featureQuery);
		//显示在页面
		model.addAttribute("features", features);
		
		//分页参数拼接对象
		StringBuilder params = new StringBuilder();
		
		//②.分页
		//设置页号
		ProductQuery productQuery = new ProductQuery();
		productQuery.setPageNo(Pagination.cpn(pageNo));
		//设置每页数
		productQuery.setPageSize(Product.FRONT_PAGE_SIZE);
		//设置Id倒序排列
		productQuery.orderbyBrandId(false);
		
		//条件 TODO
		//隐藏已选条件
		boolean flag = false;
		//定义条件Map容器
		Map<String,String> query = new LinkedHashMap<String,String>();
		
		//品牌ID
		if(null != brandId){
			productQuery.setBrandId(brandId);
			flag = true;
			model.addAttribute("brandId", brandId);
			model.addAttribute("brandName", brandName);
			query.put("品牌", brandName);
			params.append("&").append("brandId=").append(brandId).append("&brandName=").append(brandName);
		}else{
			//2.加载商品品牌
			BrandQuery brandQuery = new BrandQuery();
			brandQuery.setFields("id,name");
			brandQuery.setIsDisplay(1);//可见状态
			// 加载品牌
			List<Brand> brands = brandService.getBrandList(brandQuery);
			//显示在页面
			model.addAttribute("brands", brands);
		}
		//类型ID
		if(null != typeId){
			productQuery.setTypeId(typeId);
			flag = true;
			model.addAttribute("typeId", typeId);
			model.addAttribute("typeName", typeName);
			query.put("类型", typeName);
			params.append("&").append("typeId=").append(typeId).append("&typeName=").append(typeName);
		}else{
			//1.加载商品类型
			TypeQuery typeQuery = new TypeQuery();
			//指定查询那些字段
			typeQuery.setFields("id,name");
			typeQuery.setIsDisplay(1);// 可见1，不可见0
			List<Type> types = typeService.getTypeList(typeQuery);
			//显示在页面
			model.addAttribute("types", types);
		}
		
		model.addAttribute("flag", flag);
		//条件
		model.addAttribute("query", query);
		
		
		Pagination pagination = productService.getProductListWithPage(productQuery);
		//分页页面展示
		String url = "/product/display/list.shtml";
		pagination.pageView(url, params.toString());
		model.addAttribute("pagination", pagination);
		
		return "product/product";
	}
	
	//跳转商品详情页
	@RequestMapping(value = "/product/detail.shtml")
	public String detail(Integer id,ModelMap model,HttpServletRequest request){

		//加载购物车信息
		getBuyCartForCookie(model, request);

		//加载商品
		Product product = productService.getProductByKey(id);
		model.addAttribute("product", product);
		
		//skus
		//SkuQuery skuQuery = new SkuQuery();
		//设置商品ID
		//skuQuery.setProductId(id);
		//List<Sku> skus = skuService.getSkuList(skuQuery);
		
		//skus
		List<Sku> skus = skuService.getStock(id);
		model.addAttribute("skus", skus);
		
		//去重复
		List<Color> colors = new ArrayList<Color>();
		//遍历Sku
		for(Sku sku : skus){
			//Color color = sku.getColor();
			//判断集合中是否已经有此颜色对象
			if(!colors.contains(sku.getColor())){
				colors.add(sku.getColor());
			}
		}
		
		model.addAttribute("colors", colors);
		
		return "product/productDetail";
	}

	//加载购物车信息
	private void getBuyCartForCookie(ModelMap model, HttpServletRequest request) {
		ObjectMapper om = new ObjectMapper();
		om.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		//声明
		BuyCart buyCart = null;
		Cookie[] cookies = request.getCookies();
		if(null != cookies && cookies.length > 0){
			for(Cookie c : cookies){
				if(Constants.BUYCART_COOKIE.equals(c.getName())){
					//如果有了，就使用该购物车
					String value = c.getValue();
					try {
						buyCart = om.readValue(value, BuyCart.class);
					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				}
			}
		}
		if(null != buyCart){
			//将购物车装满
			List<BuyItem> items = buyCart.getItems();
			for(BuyItem item : items){
				Sku s = skuService.getSkuByKey(item.getSku().getId());
				item.setSku(s);
				//小计
			}
		}
		model.addAttribute("buyCart", buyCart);
		logger.info("buyCart: " + buyCart + "......");
	}


	// 第一个Springmvc
	@RequestMapping(value = "/test/springmvc.do")
	public String test(String name, Date birthday){
		System.out.println();
		return null;
	}

	// 绑定注解(局部，只针对当前Controller有作用)
	/*@InitBinder
	public void initBinder(WebDataBinder binder, WebRequest request) {
		//转换日期格式
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		
	}*/

	//加载购物车信息
	/*@RequestMapping(value = "/product/loadBuyCart.shtml")
	@ResponseBody
	public BaseResult loadBuyCart(HttpServletRequest request){
		ObjectMapper om = new ObjectMapper();
		om.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		//声明
		BuyCart buyCart = null;
		try {
			Cookie[] cookies = request.getCookies();
			if(null != cookies && cookies.length > 0){
				for(Cookie c : cookies){
					if(Constants.BUYCART_COOKIE.equals(c.getName())){
						//如果有了，就使用该购物车
						String value = c.getValue();
						try {
							buyCart = om.readValue(value, BuyCart.class);
						} catch (Exception e) {
							e.printStackTrace();
						}
						break;
					}
				}
			}
			logger.info("buyCart: " + buyCart.toString() + "......");
			return BaseResult.ok(buyCart);
		}catch (Exception e){
			e.printStackTrace();
			return BaseResult.build(500, e.getMessage());
		}
	}*/

}
